package health.lm.com.order.activity;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.rxbus.RxBus;
import com.blankj.utilcode.util.SPUtils;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.lm.sjy.titlebar.widget.CommonTitleBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import health.lm.com.component_base.base.event.BusProvider;
import health.lm.com.component_base.base.event.IBus;
import health.lm.com.component_base.base.mvp.activity.XActivity;
import health.lm.com.component_base.pay.PaymentEntity;
import health.lm.com.component_base.pay.alipay.AliPayHelper;
import health.lm.com.component_base.pay.wxpay.WxPayHelper;
import health.lm.com.order.R;
import health.lm.com.order.R2;
import health.lm.com.order.entity.SweepPayCoinEntity;
import health.lm.com.order.entity.SweepPayEntity;
import health.lm.com.order.presenter.SweepPayPresenter;
import health.lm.com.router.ARouterConstant;
import io.reactivex.functions.Consumer;

/**
 * @author GQI
 * @description 扫码支付
 * @date :2019-08-17 9:06
 */
@Route(path = ARouterConstant.SweepPayActivity)
public class SweepPayActivity extends XActivity<SweepPayPresenter> {
    @BindView(R2.id.iv_weixin)
    ImageView mIvWeixin;
    @BindView(R2.id.cb_weixin)
    CheckBox mCbWeixin;
    @BindView(R2.id.iv_alipay)
    ImageView mIvAlipay;
    @BindView(R2.id.cb_alipay)
    CheckBox mCbAlipay;
    @BindView(R2.id.tv_pay)
    TextView mTvPay;
    @BindView(R2.id.title_bar)
    CommonTitleBar mTitleBar;
    @BindView(R2.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R2.id.tv_h_money)
    TextView tvHMoney;
    @BindView(R2.id.cb_h)
    CheckBox cbH;
    @BindView(R2.id.et_money)
    EditText etMoney;
    @Autowired
    Bundle jumpBundle;
    @Autowired
    String from;
    @Autowired
    String id;

    /**
     * 支付方式 0、未选择 1、微信 2、支付宝
     */
    private int payment_type = 0;
    private SweepPayEntity entity;

    @Override
    public int getLayoutId() {
        return R.layout.activity_sweep_pay;
    }

    @Override
    public SweepPayPresenter newP() {
        return new SweepPayPresenter();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        initWidget();
        getP().getData(id);
    }

    @SuppressLint("CheckResult")
    protected void initWidget() {
        mTitleBar.setListener((v, action, extra) -> finish());
        mCbWeixin.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                payment_type = 1;
                mCbAlipay.setChecked(false);
            }
            if (!isChecked && !mCbAlipay.isChecked()) {
                mCbWeixin.setChecked(true);
            }
        });
        mCbAlipay.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                payment_type = 2;
                mCbWeixin.setChecked(false);
            }
            if (!isChecked && !mCbWeixin.isChecked()) {
                mCbAlipay.setChecked(true);
            }
        });
        mCbWeixin.setChecked(true);
        RxTextView.textChanges(etMoney)
                .compose(bindToLife())
                .debounce(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<CharSequence>() {
                    @Override
                    public void accept(CharSequence charSequence) throws Exception {
                        if(charSequence.length()>0){
                            getP().getData(id,charSequence.toString());
                        }
                    }
                });
    }


    @Override
    public void bindEvent() {
        super.bindEvent();
        BusProvider.getBus().subscribe(context, new RxBus.Callback<IBus.AbsEvent>() {
            @Override
            public void onEvent(IBus.AbsEvent absEvent) {
                if (absEvent.getTag() == 1) {
                    aliPaySuccess();
                } else if (absEvent.getTag() == 0) {
                    aliPayFail();
                }
            }
        });
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    /**
     * @param paymentEntity 支付参数
     */
    public void paymentData(PaymentEntity paymentEntity) {
        /*need_pay 1需要支付 0不需要支付 跳到支付成功*/
        //pay_type 1微信 2支付宝
        if (paymentEntity == null) {
            return;
        }
        SPUtils.getInstance().put("order_sn", paymentEntity.getOrder_sn());
        if (payment_type == 2) {
            AliPayHelper.getInstance().pay(mActivity, paymentEntity.getAli_pay_info(), payResult -> {
                getP().resultCheck(paymentEntity.getOrder_sn(), payment_type);
            });
        } else {
            WxPayHelper.getInstance().pay(mActivity, paymentEntity.getWeixin_pay_info());
        }
    }


    /**
     * 设置是否可以选择支付方式
     */
    private void setEnable(boolean enable) {
        mCbWeixin.setEnabled(enable);
        mCbAlipay.setEnabled(enable);
    }


    @OnClick(value = {R2.id.tv_pay})
    public void onClick(View v) {
        if (R.id.tv_pay == v.getId()) {
            if(etMoney.getText().toString().trim().length()>0){
                getP().getReadyPay(id, payment_type,etMoney.getText().toString(),cbH.isChecked()?"1":"0");
            }else {
                getvDelegate().toastShort("请输入支付金额");
            }
        }
    }

    public void getDataSuccess(SweepPayEntity entity) {
        if (entity == null){
            return;
        }
        this.entity = entity;
        tvShopName.setText(entity.getTitle());
        changeCoin("0",entity.getMycoin());
    }

    public void getHCoin(SweepPayCoinEntity entity){
        if (entity != null && this.entity!=null){
            changeCoin(entity.getCoin(),this.entity.getMycoin());
        }
    }

    private void changeCoin(String coin,String allCoin){
        //今日积分
        String price = "<font color=#6666666>当前优惠卡券，已优惠"+coin+"会链资产，</font><font color=#e1b65c> 当前可用"+allCoin+ "</font>";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvHMoney.setText(Html.fromHtml(price, Html.FROM_HTML_MODE_COMPACT));
        } else {
            tvHMoney.setText(Html.fromHtml(price));
        }
    }
    public void aliPaySuccess() {
        getvDelegate().toastShort("支付成功");
        finish();
    }

    public void aliPayFail() {
        getvDelegate().toastShort("支付失败请稍后再试");
    }

}
